package com.at.service.impl;

import com.at.entity.Dish;
import com.at.entity.DishDto;
import com.at.entity.DishFlavor;
import com.at.mapper.DishMapper;
import com.at.service.DishFlavorService;
import com.at.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    public void saveAndFlavor(DishDto dishDto) {
        //        1.保存菜品基本信息
        this.save(dishDto);
//        2.获取保存的菜品id
        Long dishId = dishDto.getId();
//        3.获取口味列表 遍历列表为菜品口味对象属性dishid赋值
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
//        4.批量保存菜品口味列表
        dishFlavorService.saveBatch(flavors);
    }


    @Override
    public DishDto getByidAndFlavor(Long id) {
//        1.根据id查询菜品基本信息
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
//        2.根据菜品id查询菜品口味列表数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
//        3.组装数据并返回
        dishDto.setFlavors(dishFlavorList);
        return dishDto;

    }


    @Override
    public void updateAndFlavor(DishDto dishDto) {
        //更新dish基本信息
        this.updateById(dishDto);
        //清理当前菜品对应口味数据 dish_flavor表 delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        //先删除菜品下面所有的口味
        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据 dish_flavor表insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }
}
